var express = require('express');
var router = express.Router();
var { FinanceModel } = require('../model/module/llf_db');

const alipaySdk = require('../utils/alipay.config.js');
const AlipayFormData = require('alipay-sdk/lib/form').default;

router.get('/financeList', async (req, res) => {
    const data = await FinanceModel.find({});
    res.json({
        code: 200,
        msg: '查询成功',
        data,
    })
})


router.post('/payment', function (req, res, next) {
    const { orderId, total_amount, userId } = req.body;
    // 对接支付宝
    const formData = new AlipayFormData();
    formData.setMethod('get');
    //支付成功或失败的返回链接（前端页面）
    formData.addField("returnUrl", "http://localhost:3000/llfAPi/paymentView");

    // 商单信息
    formData.addField('bizContent', {
        out_trade_no: orderId,
        product_code: "FAST_INSTANT_TRADE_PAY",
        subject: "门票",
        body: "商品详情",
        // timeout_express: "90m", 超时
        total_amount: total_amount,
        userId: userId,
    });

    // 调用支付宝 SDK 发起支付
    let result = alipaySdk.exec(
        'alipay.trade.page.pay',
        {}, // 这里可以传入额外的参数，如果需要的话
        { formData: formData }
    );


    // 处理支付结果
    result.then((resp) => {
        console.log("支付宝支付成功:", resp);
        res.send({
            success: 'true',
            code: 200,
            result: resp
        });
    }).catch((err) => {
        // 处理支付过程中的错误
        console.error("支付宝支付出现错误:", err);
        res.status(500).send({
            success: 'false',
            code: 500,
            error: '支付宝支付出现错误，请稍后再试'
        });
    });
});

module.exports = router;
